package com.example.backed.service.impl;

import com.example.backed.dto.CategoryRequest;
import com.example.backed.entity.Category;
import com.example.backed.mapper.CategoryMapper;
import com.example.backed.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    @Transactional
    public Category createCategory(CategoryRequest request) {
        Category category = new Category();
        category.setName(request.getName());
        category.setParentId(request.getParentId());
        category.setLevel(request.getLevel());
        category.setSort(request.getSort());
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.insert(category);
        return getCategory(category.getId());
    }

    @Override
    @Transactional
    public Category updateCategory(Long id, CategoryRequest request) {
        Category category = getCategory(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }

        category.setName(request.getName());
        category.setParentId(request.getParentId());
        category.setLevel(request.getLevel());
        category.setSort(request.getSort());
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.update(category);
        return getCategory(id);
    }

    @Override
    @Transactional
    public void deleteCategory(Long id) {
        Category category = getCategory(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }

        // 检查是否有子分类
        List<Category> subCategories = listSubCategories(id);
        if (!subCategories.isEmpty()) {
            throw new RuntimeException("该分类下存在子分类，无法删除");
        }

        categoryMapper.deleteById(id);
    }

    @Override
    public Category getCategory(Long id) {
        return categoryMapper.findById(id);
    }

    @Override
    public List<Category> listCategories() {
        return categoryMapper.findAll();
    }

    @Override
    public List<Category> listSubCategories(Long parentId) {
        return categoryMapper.findByParentId(parentId);
    }

    @Override
    @Transactional
    public boolean updateSort(Long id, Integer sort) {
        Category category = getCategory(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }

        return categoryMapper.updateSort(id, sort) > 0;
    }
} 